package com.sumainfor.pc.gmio.service.impl;

import com.qiniu.util.Json;
import com.sumainfor.common.Constants;
import com.sumainfor.common.entity.TemplateData;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.DateUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.*;
import com.sumainfor.common.wechat.WeChatConfig;
import com.sumainfor.pc.gmio.dao.HoEleMeterMapper;
import com.sumainfor.pc.gmio.dao.MktFeign.BillOwnerMapper;
import com.sumainfor.pc.gmio.dao.SeTenantBillMapper;
import com.sumainfor.pc.gmio.dao.UtilsMapper;
import com.sumainfor.pc.gmio.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.gmio.feign.Zfeign.ZwxTenantFeign;
import com.sumainfor.pc.gmio.service.SeEleMeterExtService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zc
 * @ClassName SeEleMeterExtServiceImpl
 * @date 2019/11/21 14:42
 * @description: TODO
 */
@Service
public class SeEleMeterExtServiceImpl implements SeEleMeterExtService {
    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(SeEleMeterExtServiceImpl.class);



    @Autowired
    ZpcMktFeign zpcMktFeign;

    @Autowired
    HoEleMeterMapper hoEleMeterMapper;

    @Autowired
    SeTenantBillMapper seTenantBillMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    BillOwnerMapper billOwnerMapper;


    @Autowired
    ZwxTenantFeign zwxTenantFeign;

    /**
     * 管家抄合租房的非智能电表
     * @param params
     * @param pager
     * @return
     */
    @Override
    public JsonResult getEleMeterNum(Map<String, Object> params, Pager pager) {
        List<String> MeterRoleList = new ArrayList<>();//最近一次抄表为租赁顾问或者管家的抄表
        MeterRoleList.add("0");
        MeterRoleList.add("2");
        JsonResult MktFeign = zpcMktFeign.getPactNumHou(params,pager);//获取需要管家抄表的房源集合
        Map<String,Object> MktMap = (Map<String, Object>) MktFeign.get("result");
        List<Map<String,Object>> MktList = (List<Map<String, Object>>) MktMap.get("dataList");
        if (MktList.size()>0) {
            for (Map<String, Object> map1 : MktList) {
                List<Map<String, Object>> getHouInfoNum = zpcMktFeign.getHouInfoNum(map1);//查询该房源下有多少房间(包括整租)
                List<Map<String,Object>> getBatchIdList = new ArrayList<>();
                for (Map<String, Object> getHouInfoMap : getHouInfoNum) {
                    String HouInfoIds =MapUtils.getString(getHouInfoMap,"HouInfoId");
                    if (HouInfoIds.substring(HouInfoIds.length()-1,HouInfoIds.length()).equals("A")){
                        getHouInfoMap.put("MeterRoleList",MeterRoleList);
                      Map<String,Object> getHouInfoEleMap =  hoEleMeterMapper.getHouInfoEle(getHouInfoMap);//查询最近一次租赁顾问或者管家抄的房间的表,拿到抄表批次编号,查询每个房间的抄表记录
                        getBatchIdList = hoEleMeterMapper.getBatchIdList(getHouInfoEleMap);//个房间的抄表数
                    }
                }
                if (getBatchIdList.size()>0) {
                    map1.put("EleList", getBatchIdList);
                }
            }
        }
     return MktFeign;
   }

    /**
     * 秘书抄电的房源
     * @param params
     * @param pager
     * @return
     */
    @Override
    public JsonResult getEleSecretary(Map<String, Object> params, Pager pager) {
        JsonResult MktFeign = zpcMktFeign.getHouId(params,pager);//获取需要秘书抄表的房源集合
        Map<String,Object> MktMap = (Map<String, Object>) MktFeign.get("result");
        List<Map<String,Object>> MktList = (List<Map<String, Object>>) MktMap.get("dataList");
        if (MktList.size()>0){
            for (Map<String,Object> map1:MktList){
                String HouInfoIdS = MapUtils.getString(map1,"HouInfoId");
                String HouInfoIdss = HouInfoIdS.replace(HouInfoIdS.substring(HouInfoIdS.length() - 1, HouInfoIdS.length()), "Z");
                map1.put("HouInfoId",HouInfoIdss);
                map1.put("MeterRole",1);
                Map<String,Object> getHouInfoEle = hoEleMeterMapper.getHouInfoEle(map1);//查询当前房源的最近一次的抄表数;
                if (getHouInfoEle!=null) {
                    map1.putAll(getHouInfoEle);
                }
            }
        }
        return MktFeign;

    }

    /**
     * 管家记录抄表数
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult getEleBrowse(Map<String, Object> params) {
        JsonResult result = new JsonResult();
//
//        参数格式
//        params{
//            "EleHouList": [
//                        {
//                            "HouId":"FY-201911170011",
//                            "HouInfoId":"TFY0001阿里0170001Z",
//                            "EleData":{
//                                    "LastMonthEleSum":"10",
//                                    "LastMonthElePeak":"10",
//                                    "LastMonthEleFlat":"10",
//                                    "ThisMonthEleSum":"20",
//                                    "ThisMonthElePeak":"20",
//                                    "ThisMonthEleFlat":"20"
//                                    "roomData":[
//                            {
//                                "HouInfoId":
//                                "LastMonthEleSum":
//                                "ThisMonthEleSum"
//                            }
//                                            ]
//
//                        },
//
//                        }
//
//
//
//                                ]
//
//
//
//        }
        /**
         * 加锁操作
         */
        lock.lock();
        try {
  //          String EleUUID ="";//电费抄表编号
//            String Eleus  = "";//电费抄表批次编号
//            //获取账单编号
//            Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "BiId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_tenant_bill");
//            }});
//
//            String Eleus  = "";//电费抄表批次编号
//            //电
//            Map<String,Object> Eleuuid =utilsMapper.getUUID(new HashMap<String,Object>(){{
//                put("uuid", "ElemeId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_ele_meter");
//            }});





            //获取当前时间
            Date nowTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String GenerateTimeNow = sdf.format(nowTime);//租赁顾问签约抄水电燃,抄表记录的时间默认一致,

            //账单生成日
            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format1.parse(GenerateTimeNow);

//            int numberss = 0;
//            if(Eleuuid!=null){
//                numberss=Integer.valueOf(Eleuuid.get("uuid").toString());
//                Eleus = ComUtils.getLocalTrmSeqNum("BA0",numberss);
//            }else{
//                Eleus = ComUtils.getLocalTrmSeqNum("BA0",0);
//            }

           List<Map<String,Object>> EleHouList = (List<Map<String, Object>>) params.get("EleHouList");//获取本次抄表的房源集合
            if (EleHouList.size()>0){
                for (Map<String,Object> EleHouMap:EleHouList) {



                    String Eleus  = "";//电费抄表批次编号
                    //电
                    Map<String,Object> Eleuuid =utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "ElemeId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_ele_meter");
                    }});
                    int numberss = 0;
                    if(Eleuuid!=null){
                        numberss=Integer.valueOf(Eleuuid.get("uuid").toString());
                        Eleus = ComUtils.getLocalTrmSeqNum("BA0",numberss);
                    }else{
                        Eleus = ComUtils.getLocalTrmSeqNum("BA0",0);
                    }





                    Map<String,Object> EleData = (Map<String, Object>) EleHouMap.get("EleData");//获取抄表数集合
                    List<Map<String,Object>> roomData  = (List<Map<String, Object>>) EleData.get("roomData");//获取除公共区域外其他房间的抄表数
                   // Double ElePooled = CompuUtils.reduce(MapUtils.getDouble(EleData,"ThisMonthEleSum"),MapUtils.getDouble(EleData,"LastMonthEleSum"));

                    Double lastSum = new Double("0");
                    Double NowSum = new Double("0");
                    for (Map<String,Object> map5:roomData){
                        lastSum = CompuUtils.add(lastSum,MapUtils.getDouble(map5,"LastMonthEleSum"));
                        NowSum = CompuUtils.add(NowSum,MapUtils.getDouble(map5,"ThisMonthEleSum"));
                    }
                    //计算本次总的均摊电量
                    Double ElePooled =  CompuUtils.reduce(CompuUtils.reduce(MapUtils.getDouble(EleData,"ThisMonthEleSum"),NowSum),CompuUtils.reduce(MapUtils.getDouble(EleData,"LastMonthEleSum"),lastSum));


                    List<Map<String,Object>> getHouPact = zpcMktFeign.getHouPact(EleHouMap);//获取房源在租租客
                    //获取在租房间本次管家抄表的均摊电量
                    Double perELeSum = CompuUtils.div(ElePooled,new Double(getHouPact.size()),2);
                    for (Map<String,Object> map1:getHouPact) {//便利当前房源再组租客

                        //Double perELeMoneys =perELeSum;
                        Double perELeMoneys = CompuUtils.mul(perELeSum,MapUtils.getDouble(map1,"EleFee"));

                        for (Map<String,Object> roomMap:roomData){
                            if (MapUtils.getString(map1,"HouInfoId").equals(MapUtils.getString(roomMap,"HouInfoId"))){

                                //perELeMoneys = CompuUtils.reduce(MapUtils.getDouble(roomMap,"ThisMonthEleSum"),MapUtils.getDouble(roomMap,"LastMonthEleSum"))
                                perELeMoneys=  CompuUtils.add(perELeMoneys,CompuUtils.mul(CompuUtils.reduce(MapUtils.getDouble(roomMap,"ThisMonthEleSum"),MapUtils.getDouble(roomMap,"LastMonthEleSum")),MapUtils.getDouble(map1,"EleFee")));

                            }
                        }



                        StringBuffer BillExpains = new StringBuffer();//账单说明
                        List<Map<String,Object>> getElePoodList = hoEleMeterMapper.getHouInEle(map1);//获取房间已生成均摊未生成账单的抄表编号
                        if (getElePoodList.size()>0){
                            for (Map<String,Object> map2:getElePoodList){
                                perELeMoneys = CompuUtils.add(perELeMoneys,MapUtils.getDouble(map2,"perELeMoney"));//获取当前在租组可所租房间的之前的未生成账单的均摊两

                                BillExpains.append(MapUtils.getString(map2,"ElemeId")).append(";");//帐单金额说明

                                //修改未生成账单的均摊量为已生成账单
                                Map<String,Object> EleMaps = new HashMap<>();
                                EleMaps.put("term","4");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                                EleMaps.put("fnc",
                                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                                ParamsCommon.commonUpdateParms(EleMaps);
                                EleMaps.put("IfGenerate",1);//1表示生成账单 0未生成账单
                                EleMaps.put("ElemeId",map2.get("ElemeId"));//电抄表编号
                                Integer a1 = hoEleMeterMapper.updateHoEleDelfg(EleMaps);
                                if (a1>0){
                                    result.putSuccess("修改该房源之前未生成均摊的电量成功");
                                }else {
                                    return result.putFailed("修改该房源之前未生成均摊的电量失败");
                                }

                            }

                        }

//                        String  BiIdUUID = "";//电费费账单编号
                        Map<String,Object> billMap = new HashMap<>();
                        String  BiIdUUID = "";//电费费账单编号
                        //获取账单编号
                        Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                            put("uuid", "BiId");
                            put("database", Constants.DATA_SOURCE_GMIO);
                            put("surface", "tcgmio_tenant_bill");
                        }});
                        if(BiIduuid!=null){
                            int number=Integer.valueOf(BiIduuid.get("uuid").toString());
                            BiIdUUID= ComUtils.getLocalTrmSeqNum("BIELEGJ",number);

                        }else{
                            BiIdUUID=ComUtils.getLocalTrmSeqNum("BIELEGJ",0);
                        }
                        billMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                        billMap.put("fnc",
                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                        ParamsCommon.commonInsertParms(billMap);
                        billMap.put("BiId",BiIdUUID);//账单编号
                        billMap.put("CorId",map1.get("CorId"));//账单归属公司
                        billMap.put("BiName","管家抄表生成租客电费账单");//账单名称
                        billMap.put("IfTemporary",0);//是否是临时账单0否 1 是
                        billMap.put("BiType",2);//账单类型 2公共事业费
                        billMap.put("Source",Eleus);//账单来源
                        billMap.put("PubType",2);//公共事业费类型1水费 2电费
                        billMap.put("BiMoney",perELeMoneys);//账单金额,每个租客本次抄表需支付金额
                        billMap.put("BillExplain",BillExpains.toString());//账单金额说明
                       // billMap.put("BiGenerated",GenerateTimeNow);//账单生成日
                        //billMap.put("EndTime", DateUtils.addDateDays(date,15));//账单结束日
                        billMap.put("BiGenerated",EleData.get("GenerateTime"));//账单生成日
                        billMap.put("EndTime",GenerateTimeNow);//账单结束日
                        billMap.put("LateDay", DateUtils.addDateDays(date,15));//账单最晚付款日
                        billMap.put("TenId",map1.get("TenId"));//租客编号
                        billMap.put("HouId",map1.get("HouId"));//房源编号
                        billMap.put("HouInfoId",map1.get("HouInfoId"));//房源详表编号
                        billMap.put("CreateType",2);//账单创建人类型1系统 2 人为
                        billMap.put("Create",ContextUtils.getUserId());//账单创建人
                        billMap.put("ExpTime",DateUtils.addDateDays(date,15));//逾期开始时间
                        billMap.put("Status",1);//1待支付
                        Integer a3 = seTenantBillMapper.addTenantBill(billMap);//新增电费账单
                        if (a3>0){
                            result.putSuccess("新增电费账单成功");
                            JsonResult OpenResult = zwxTenantFeign.getTenOpenId(billMap);
                            Map<String,Object> ceshiMap = (Map<String, Object>) OpenResult.get("result");
                            //推送微信模板
                            String touser=ceshiMap.get("uopid").toString();//租客的openid
                            Map<String, TemplateData> param = new HashMap<>();
                            param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的租客，您有新的待支付的电费账单。请您尽快支付。如有异议，请联系您的租赁顾问人员为您服务。\n", "#4876FF"));
                            param.put("keyword1", new TemplateData(billMap.get("BiGenerated").toString(), "#4876FF"));//账单日期
                            param.put("keyword2", new TemplateData("0", "#4876FF"));//逾期天数
                            param.put("keyword3", new TemplateData(billMap.get("BiGenerated").toString()+"-"+billMap.get("LateDay").toString(), "#4876FF"));//账单周期
                            param.put("keyword4", new TemplateData(billMap.get("BiMoney").toString(), "#4876FF"));//应缴明细
                            log.info("param:"+net.sf.json.JSONObject.fromObject(param));
                            Jsapi_ticketUtil.sendTemplate(touser, WeChatConfig.GUANMI_ID,"http://www.4006269069.net/#/allBill","#4876FF", net.sf.json.JSONObject.fromObject(param));
                        }else {
                            return result.putFailed("新增电费账单失败");
                        }

                    }

                    Map<String,Object> EleWater = new HashMap<>();//先生成公共区域的
                    EleWater.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    EleWater.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(EleWater);
                    EleWater.put("ElemeId", ComUtils.getLocalTrmSeqNum("EM" + 0, numberss));//电费抄表编号(公共区域)
                    EleWater.put("BatchId", Eleus);//批次编号
                    EleWater.put("HouId", EleHouMap.get("HouId"));//房源编号
                    EleWater.put("HouInfoId", EleHouMap.get("HouInfoId"));//公共区域的房源详表编号
                    EleWater.put("IfOperaType", 1);//是否整租0否1是
                    EleWater.put("LastMonthEleSum", EleData.get("LastMonthEleSum"));//上次总表
                  //  EleWater.put("LastMonthElePeak", EleData.get("LastMonthElePeak"));//上次峰表
                  //  EleWater.put("LastMonthEleFlat", EleData.get("LastMonthEleFlat"));//上次谷表
                    EleWater.put("ThisMonthEleSum", EleData.get("ThisMonthEleSum"));//总表
                   // EleWater.put("ThisMonthElePeak", EleData.get("ThisMonthElePeak"));//峰表
                  //  EleWater.put("ThisMonthEleFlat", EleData.get("ThisMonthEleFlat"));//谷表
                    EleWater.put("GenerateTime", GenerateTimeNow);//抄表日期
                    EleWater.put("perELeSum", ElePooled);//公摊电量
                    EleWater.put("MeterRole", 2);//服务管家
                    EleWater.put("Recorder", ContextUtils.getUserId());//记录人编号
                    EleWater.put("IfGenerate", 1);//是否生成账单0未生成 1已生成
                    Integer a4 = hoEleMeterMapper.addHoEleMeter(EleWater);//生成公共区域
                    if (a4>0){
                        result.putSuccess("新增公共区域抄表成功");
                    }else {
                        return result.putFailed("新增公共区域抄表失败");
                    }

                    for (int i = 0;i<roomData.size();i++){
                        Map<String,Object> roomMapone = new HashMap<>();
                        roomMapone.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                        roomMapone.put("fnc",
                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                        ParamsCommon.commonInsertParms(roomMapone);
                        roomMapone.put("ElemeId", ComUtils.getLocalTrmSeqNum("EM" + (i+1), numberss));//电费抄表编号(公共区域)
                        roomMapone.put("BatchId", Eleus);//批次编号
                        roomMapone.put("HouId", EleHouMap.get("HouId"));//房源编号
                        roomMapone.put("HouInfoId",roomData.get(i).get("HouInfoId"));//其他房间的房源详表编号
                        roomMapone.put("IfOperaType", 0);//是否整租0否1是
                        roomMapone.put("LastMonthEleSum", roomData.get(i).get("LastMonthEleSum"));//上次总表
                       // roomMapone.put("LastMonthElePeak", EleData.get("LastMonthElePeak"));//上次峰表
                       // roomMapone.put("LastMonthEleFlat", EleData.get("LastMonthEleFlat"));//上次谷表
                        roomMapone.put("ThisMonthEleSum", roomData.get(i).get("ThisMonthEleSum"));//总表
                       // roomMapone.put("ThisMonthElePeak", EleData.get("ThisMonthElePeak"));//峰表
                       // roomMapone.put("ThisMonthEleFlat", EleData.get("ThisMonthEleFlat"));//谷表
                        roomMapone.put("MeterRole", 2);//服务管家
                        roomMapone.put("GenerateTime", GenerateTimeNow);//抄表日期
                        roomMapone.put("Recorder", ContextUtils.getUserId());//记录人编号
                        roomMapone.put("IfGenerate", 1);//是否生成账单0未生成 1已生成
                        for(Map<String,Object> map8:getHouPact){
                            if(roomMapone.get("HouInfoId").equals(MapUtils.getString(map8,"HouInfoId"))){
                                roomMapone.put("perELeSum", perELeSum);//房间均摊电量
                                roomMapone.put("perELeMoney", CompuUtils.mul(perELeSum,MapUtils.getDouble(map8,"EleFee")));//房间均摊金额

                            }

                        }
                        Integer a5 = hoEleMeterMapper.addHoEleMeter(roomMapone);//生成房间的均摊电量
                        if (a5>0){
                            result.putSuccess("新增房间抄表成功");
                        }else {
                            return result.putFailed("新增房间抄表失败");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        } finally {
            lock.unlock();
        }


        return result;
    }

    /**
     * 秘书记录本次抄表数
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult addEleClerk(Map<String, Object> params) {

        JsonResult result = new JsonResult();
//
//        参数格式
//                params:{
//                 "EleHouList":[
//                    {
//                        HouId
//                        HouInfoId
//                       `LastMonthEleSum` float DEFAULT NULL COMMENT '上月总表',
//                       `LastMonthElePeak` float DEFAULT NULL COMMENT '上月峰时',
                    //  `LastMonthEleFlat` float DEFAULT NULL COMMENT '上月谷时',
                    //  `ThisMonthEleSum` float DEFAULT NULL COMMENT '总表   （不能低于上月）',
                    //  `ThisMonthElePeak` float DEFAULT NULL COMMENT '峰时   （不能低于上月）',
                    //  `ThisMonthEleFlat` float DEFAULT NULL COMMENT '谷时'
//                        StaTime
//                        EndTime
//                        BillMoney
//                    },
//                    {
//                        HouId
//                         HouInfoId
//                        LastMonthRead
//                        ThisMonthRead
//                        StaTime
//                         EndTime
//                        BillMoney
//                    }
//
//
//
//
//
//
//                         ]
//
//
//                }




        lock.lock();
        try {

//            String BiOutIdUUID = "";//账单支出编号
//            String  BiIdUUID ="";//租客编号
//            String ElemeIdUUID = "";//燃气抄表编号
//            String BatchIdUUID = "";//燃气抄表批次编号




//            String BiOutIdUUID = "";//账单支出编号
//            Map<String, Object> BiOutIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "BiOutId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_bill_outlay");
//            }});
//            String  BiIdUUID ="";//租客编号
//            Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "BiId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_tenant_bill");
//            }});

//            String ElemeIdUUID = "";//燃气抄表编号
//            String BatchIdUUID = "";//燃气抄表批次编号
//            Map<String, Object> ElemeIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
//                put("uuid", "ElemeId");
//                put("database", Constants.DATA_SOURCE_GMIO);
//                put("surface", "tcgmio_ele_meter");
//            }});
//            if(ElemeIduuid!=null){
//                int number=Integer.valueOf(ElemeIduuid.get("uuid").toString());
//                ElemeIdUUID= ComUtils.getLocalTrmSeqNum("EM0",number);
//                BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",number);
//            }else{
//                ElemeIdUUID=ComUtils.getLocalTrmSeqNum("EM0",0);
//                BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",0);
//            }


            Date nowTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String GenerateTimes = sdf.format(nowTime);//记录当前时间



            Integer a = new Integer("0");
            List<Map<String,Object>> EleHouList = (List<Map<String, Object>>) params.get("EleHouList");//获取本次记录的房源燃气表集合
            if (EleHouList.size()>0){
                for (Map<String,Object> EleHouMap:EleHouList){


                    String ElemeIdUUID = "";//燃气抄表编号
                    String BatchIdUUID = "";//燃气抄表批次编号
                    Map<String, Object> ElemeIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "ElemeId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_ele_meter");
                    }});
                    if(ElemeIduuid!=null){
                        int number=Integer.valueOf(ElemeIduuid.get("uuid").toString());
                        ElemeIdUUID= ComUtils.getLocalTrmSeqNum("EM0",number);
                        BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",number);
                    }else{
                        ElemeIdUUID=ComUtils.getLocalTrmSeqNum("EM0",0);
                        BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0",0);
                    }


                    Integer aaa = new Integer("0");

                    Double GasBiMoney = new Double("0");
                    //获取当前房源签署的公司号
                    JsonResult CorIdResult = zpcMktFeign.getCorId(EleHouMap);
                    Map<String,Object> CorIdMap = (Map<String, Object>) CorIdResult.get("result");



                    JsonResult MktResult = zpcMktFeign.getInfoStatus(EleHouMap);
                    Map<String,Object> getInfoMap = (Map<String, Object>) MktResult.get("result");

                    Map<String,Object> OutLaymap = new HashMap<>();
                    String BiOutIdUUID = "";//账单支出编号
                    Map<String, Object> BiOutIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "BiOutId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_bill_outlay");
                    }});
                    if(BiOutIduuid!=null){
                        int numberss=Integer.valueOf(BiOutIduuid.get("uuid").toString());
                        BiOutIdUUID = ComUtils.getLocalTrmSeqNum("zcEle",numberss);
                    }else{
                        BiOutIdUUID = ComUtils.getLocalTrmSeqNum("zcEle",0);
                    }
                    OutLaymap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    OutLaymap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(OutLaymap);
                    OutLaymap.put("BiOutId",BiOutIdUUID);//账单编号
                    OutLaymap.put("CorId",CorIdMap.get("CorId"));//归属公司
                    OutLaymap.put("Period",1);//账期
                    OutLaymap.put("BiOutName","秘书抄表生成电费账单");//账单名称
                    OutLaymap.put("IfTemporary",0);//0否临时账单 1是
                    OutLaymap.put("BiOutType",4);//4账单类型 公共事业费
                    OutLaymap.put("PubType",2);//电费
                    OutLaymap.put("BillExplain","秘书抄表生成电费账单");//金额说明
                    OutLaymap.put("StartTime",EleHouMap.get("StaTime"));//账单生成日
                    OutLaymap.put("EndTime",EleHouMap.get("EndTime"));//账单结束日
                    OutLaymap.put("LateDay",EleHouMap.get("EndTime"));//账单最晚付款日
                    OutLaymap.put("IfAdjust",0);//当前账单是否可以调整0否
                    OutLaymap.put("StemType",3);//支出类型 3租客
                    OutLaymap.put("HouId",EleHouMap.get("HouId"));//房源id
                    OutLaymap.put("HouInfoId",EleHouMap.get("HouInfoId"));//房源详表编号
                    OutLaymap.put("CreateType",2);//账单创建人类型1系统 2 人为
                    OutLaymap.put("Applicant", ContextUtils.getUserId());//申请人
                    OutLaymap.put("Status",1);//账单状态1待支付




                    Map<String,Object> billMap = new HashMap<>();
                    String  BiIdUUID ="";//租客编号
                    Map<String, Object> BiIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "BiId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_tenant_bill");
                    }});
                    if(BiIduuid!=null){
                        int number=Integer.valueOf(BiIduuid.get("uuid").toString());
                        BiIdUUID = ComUtils.getLocalTrmSeqNum("BIEleMS",number);
                    }else{
                        BiIdUUID = ComUtils.getLocalTrmSeqNum("BIEleMS",0);
                    }
                    billMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    billMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(billMap);
                    billMap.put("BiId",BiIdUUID);//账单编号
                    billMap.put("CorId",CorIdMap.get("CorId"));//账单归属公司
                    billMap.put("BiName","秘书抄表生成租客电费账单");//账单名称
                    billMap.put("IfTemporary",0);//是否是临时账单0否 1 是
                    billMap.put("BiType",2);//账单类型 2公共事业费
                    billMap.put("PubType",2);//公共事业费类型1水费 2电费 3燃气
                    billMap.put("BillExplain","秘书抄表生成租客电费账单");//账单金额说明
                    billMap.put("BiGenerated",EleHouMap.get("StaTime"));//账单生成日
                    billMap.put("EndTime", EleHouMap.get("EndTime"));//账单结束日
                    billMap.put("LateDay", EleHouMap.get("EndTime"));//账单最晚付款日
                    billMap.put("HouId",EleHouMap.get("HouId"));//房源编号
                    billMap.put("HouInfoId",EleHouMap.get("HouInfoId"));//房源详表编号
                    billMap.put("CreateType",2);//账单创建人类型1系统 2 人为
                    billMap.put("Create",ContextUtils.getUserId());//账单创建人
                    billMap.put("ExpTime",EleHouMap.get("EndTime"));//逾期开始时间
                    billMap.put("Status",1);//1待支付


                    if (getInfoMap==null){//只用生成唐巢支出
                        OutLaymap.put("Relation",ElemeIdUUID);//关联账单,本次抄表记录
                        OutLaymap.put("BiMoney",EleHouMap.get("BillMoney"));//账单金额
                        GasBiMoney = MapUtils.getDouble(OutLaymap,"BiMoney");
                        Integer a1 = billOwnerMapper.AddBillOwner(OutLaymap);//生成支出账单
                        if (a1>0){
                         //   result.putSuccess("生成支出账单成功");
                            aaa++;
                        }else{
                            return result.putFailed("生成支出账单失败");
                        }


                    }else{//不仅要生成唐巢支出,也要生成租客账单(该房源已经出租)

                        OutLaymap.put("Relation",ElemeIdUUID);//关联账单,本次抄表记录
                        OutLaymap.put("BiMoney",EleHouMap.get("BillMoney"));//账单金额
                        OutLaymap.put("StemId",getInfoMap.get("TenId"));//支出关联人编号,有租客
                        Integer a2 = billOwnerMapper.AddBillOwner(OutLaymap);//生成支出账单
                        if (a2>0){
                           // result.putSuccess("生成支出账单成功");
                            aaa++;
                        }else{
                            return result.putFailed("生成支出账单失败");
                        }




                        //先查秘书
                        String StartTime = MapUtils.getString(getInfoMap,"StartTime");//合同的开始时间
                        Map<String,Object> mishuMap =new HashMap<>();
                        mishuMap.put("StartTime",StartTime);
                        mishuMap.put("HouInfoId",EleHouMap.get("HouInfoId"));
                        mishuMap.put("MeterRole",1);
                        Map<String,Object> getHouInfoGas= new HashMap<>();

                        getHouInfoGas= hoEleMeterMapper.getHouInfoEle(mishuMap);//上次抄表人是秘书
                        if (getHouInfoGas==null){
                            mishuMap.put("MeterRole",0);
                            mishuMap.remove("StartTime");
                            getHouInfoGas = hoEleMeterMapper.getHouInfoEle(mishuMap);//上次抄表人租赁顾问

                        }
                        //秘书查不到就差顾问






                     //   Map<String,Object> getHouInfoGas = hoEleMeterMapper.getHouInfoEle(EleHouMap);//查询上次抄表人
                        if (MapUtils.getInteger(getHouInfoGas,"MeterRole")==0){//租赁顾问

                            billMap.put("Source",ElemeIdUUID);//账单来源
                            billMap.put("TenId",getInfoMap.get("TenId"));//租客编号
                            billMap.put("BiMoney",CompuUtils.mul(CompuUtils.reduce( MapUtils.getDouble(EleHouMap,"ThisMonthEleSum"),MapUtils.getDouble(getHouInfoGas,"ThisMonthEleSum")),MapUtils.getDouble(getInfoMap,"EleFee")));//账单金额,每个租客本次抄表需支付金额
                            GasBiMoney = MapUtils.getDouble(billMap,"BiMoney");
                            Integer a4 =  seTenantBillMapper.addTenantBill(billMap);
                            if (a4>0){
                                //result.putSuccess("生成租客账单成功");
                                aaa++;
                                JsonResult OpenResult = zwxTenantFeign.getTenOpenId(billMap);
                                Map<String,Object> ceshiMap = (Map<String, Object>) OpenResult.get("result");
                                //推送微信模板
                                String touser=ceshiMap.get("uopid").toString();//租客的openid
                                Map<String, TemplateData> param = new HashMap<>();
                                param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的租客，您有新的待支付的电费账单。请您尽快支付。如有异议，请联系您的租赁顾问人员为您服务。\n", "#4876FF"));
                                param.put("keyword1", new TemplateData(billMap.get("BiGenerated").toString(), "#4876FF"));//账单日期
                                param.put("keyword2", new TemplateData("0", "#4876FF"));//逾期天数
                                param.put("keyword3", new TemplateData(billMap.get("BiGenerated").toString()+"-"+billMap.get("LateDay").toString(), "#4876FF"));//账单周期
                                param.put("keyword4", new TemplateData(billMap.get("BiMoney").toString(), "#4876FF"));//应缴明细
                                log.info("param:"+net.sf.json.JSONObject.fromObject(param));
                                Jsapi_ticketUtil.sendTemplate(touser, WeChatConfig.GUANMI_ID,"http://www.4006269069.net/#/allBill","#4876FF", net.sf.json.JSONObject.fromObject(param));

                            }else{
                                return result.putFailed("生成租客账单失败");
                            }










                        }else if(MapUtils.getInteger(getHouInfoGas,"MeterRole")==1){//秘书

                            billMap.put("Source",ElemeIdUUID);//账单来源
                            billMap.put("BiMoney",EleHouMap.get("BillMoney"));//账单金额,每个租客本次抄表需支付金额
                            GasBiMoney = MapUtils.getDouble(billMap,"BiMoney");
                            billMap.put("TenId",getInfoMap.get("TenId"));//租客编号
                            Integer a3 =  seTenantBillMapper.addTenantBill(billMap);
                            if (a3>0){
                                //result.putSuccess("生成租客账单成功");
                                aaa++;

                                JsonResult OpenResult = zwxTenantFeign.getTenOpenId(billMap);
                                Map<String,Object> ceshiMap = (Map<String, Object>) OpenResult.get("result");
                                //推送微信模板
                                String touser=ceshiMap.get("uopid").toString();//租客的openid
                                Map<String, TemplateData> param = new HashMap<>();
                                param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的租客，您有新的待支付的电费账单。请您尽快支付。如有异议，请联系您的租赁顾问人员为您服务。\n", "#4876FF"));
                                param.put("keyword1", new TemplateData(billMap.get("BiGenerated").toString(), "#4876FF"));//账单日期
                                param.put("keyword2", new TemplateData("0", "#4876FF"));//逾期天数
                                param.put("keyword3", new TemplateData(billMap.get("BiGenerated").toString()+"-"+billMap.get("LateDay").toString(), "#4876FF"));//账单周期
                                param.put("keyword4", new TemplateData(billMap.get("BiMoney").toString(), "#4876FF"));//应缴明细
                                log.info("param:"+net.sf.json.JSONObject.fromObject(param));
                                Jsapi_ticketUtil.sendTemplate(touser, WeChatConfig.GUANMI_ID,"http://www.4006269069.net/#/allBill","#4876FF", net.sf.json.JSONObject.fromObject(param));





                            }else{
                                return result.putFailed("生成租客账单失败");
                            }

                        }










                    }


                    Map<String,Object> GasMap = new HashMap<>();//记录燃不生成账单
                    GasMap.put("term", "2");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    GasMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(GasMap);
                    GasMap.put("ElemeId",ElemeIdUUID);//燃气费抄表编号
                    GasMap.put("BatchId",BatchIdUUID);//批次编号
                    GasMap.put("HouId",EleHouMap.get("HouId"));//房源编号
                    GasMap.put("HouInfoId",EleHouMap.get("HouInfoId"));//房源详表编号
                    GasMap.put("IfOperaType",1);//是否整租0否1是
                    GasMap.put("LastMonthEleSum",EleHouMap.get("LastMonthEleSum"));//上次总
                    GasMap.put("LastMonthElePeak",EleHouMap.get("LastMonthElePeak"));//峰
                    GasMap.put("LastMonthEleFlat",EleHouMap.get("LastMonthEleFlat"));//谷
                    GasMap.put("ThisMonthEleSum",EleHouMap.get("ThisMonthEleSum"));//本次总
                    GasMap.put("ThisMonthElePeak",EleHouMap.get("ThisMonthElePeak"));//本次峰
                    GasMap.put("ThisMonthEleFlat",EleHouMap.get("ThisMonthEleFlat"));//本次谷
                    GasMap.put("StaTime",EleHouMap.get("StaTime"));//总表数
                    GasMap.put("EndTime",EleHouMap.get("EndTime"));//总表数
                    GasMap.put("MeterRole",1);//抄表人角色1 服务秘书
                    GasMap.put("BillMoney",GasBiMoney);//账单金额111111111111111111111111
                    GasMap.put("GenerateTime",GenerateTimes);//抄表日期
                    GasMap.put("Recorder", ContextUtils.getUserId());//记录人编号
                    GasMap.put("IfApportion",0);//是否需要分摊0否1是
                    GasMap.put("IfGenerate",1);//是否生成账单
                    Integer a3= hoEleMeterMapper.addHoEleMeter(GasMap);//新增燃气抄表记录
                    if (a3>0){
                        result.putSuccess("新增电表成功");
                        aaa++;
                    }else{
                        return result.putFailed("新增电表失败");
                    }



                    if(getInfoMap==null){
                        if (aaa==2){
                            a++;
                        }else{
                            return result.putFailed("本次抄表失败");
                        }

                    }else {
                        if (aaa==3){
                            a++;
                        }else{
                            return result.putFailed("本次抄表失败");
                        }

                    }
                }

                if(a==EleHouList.size()){
                    result.putSuccess("抄表成功");
                }else{
                    return result.putFailed("抄表失败");
                }

            }
        }catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事务回滚
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 管家退租查询上期电费(如果整租上期为租赁或秘书)(如果合租非智能上期为租赁或管家)
     * @param params
     * @return
     */
    @Override
    public JsonResult getLastEleLease(Map<String, Object> params) {
    JsonResult result = new JsonResult();
        String a = MapUtils.getString(params,"HouInfoId");
    if(a.substring(a.length()-1,a.length()).equals("Z")){
        result.put(hoEleMeterMapper.getHouInfoEle(params));
    }else{
        Map<String,Object> getHouInfoEle = hoEleMeterMapper.getHouInfoEle(params);
        if (getHouInfoEle!=null){
            List<Map<String,Object>> getBatchIdList = hoEleMeterMapper.getBatchIdList(getHouInfoEle);//统一批次下的抄表
            result.put(getBatchIdList);
        }
    }
    return result;
    }

}
